/**
 * ========================================================================================================================
 * 通过签名方式调用API，支持平台的任意API。
 * 签名文档：https://help.aliyun.com/document_detail/144904.html
 * ========================================================================================================================
 */

import CryptoJS from 'crypto-js'

//AccessKeyID
const accessKeyId = "LTAI5tPkqR2c7xhGfk9Wiwrw";
//AccessKeySecret
const accessKeySecret = "2OsS0N0I5qQ4TkK8RLZnmCutscymcB";

function callApi(endpoint, action, version, params, callback) {
  const API_HTTP_METHOD = "POST";

  const request_ = {};
  //系统参数
  request_["SignatureMethod"] = "HMAC-SHA1";
  request_["SignatureNonce"] = Math.round(Math.random() * 100000000000000);
  request_["AccessKeyId"] = accessKeyId;
  request_["SignatureVersion"] = "1.0";
  request_["Timestamp"] = getISOTime();
  request_["Format"] = "JSON";
  request_["RegionId"] = "cn-shanghai";
  request_["Version"] = version;
  request_["Action"] = action;
  
  // 业务参数
  if(params) {
    for(let key in params) {
      request_[key] = params[key];
    }
  }

  // 参数排序
  const sortedParams = Object.keys(request_)
    .sort()
    .reduce((acc, key) => {
      acc[key] = request_[key];
      return acc;
    }, {});

  // 构建查询字符串
  const queryString = Object.entries(sortedParams)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');

  // 构建签名字符串
  const stringToSign = `${API_HTTP_METHOD}&${encodeURIComponent('/')}&${encodeURIComponent(queryString)}`;
  
  // 计算签名
  const signature = CryptoJS.HmacSHA1(stringToSign, accessKeySecret + '&')
    .toString(CryptoJS.enc.Base64);

  // 生成最终URL
  const url = `https://${endpoint}/?Signature=${encodeURIComponent(signature)}&${queryString}`;

  // 发送请求
  uni.request({
    url,
    method: API_HTTP_METHOD,
    timeout: 5000,
    success: (res) => {
      callback && callback(res);
    },
    fail: (err) => callback && callback(err)
  });
}

/**
 * 人脸识别功能
 * @param {string} imageUrl 需要识别的图片URL
 * @param {Function} callback 结果回调函数
 */
function callRecognizeFace(imageUrl, callback) {
  const endpoint = "facebody.cn-shanghai.aliyuncs.com";
  const action = "RecognizeFace";
  const version = "2019-12-30";
  const params = {
    ImageURL: imageUrl
  };

  callApi(endpoint, action, version, params, callback);
}

/**
 * 人脸比对功能
 * @param {string} imageUrl1 第一张人脸图片URL
 * @param {string} imageUrl2 第二张人脸图片URL
 * @param {Function} callback 结果回调函数
 */
function compareFace(imageUrl1, imageUrl2, callback) {
  const endpoint = "facebody.cn-shanghai.aliyuncs.com";
  const action = "CompareFace";
  const version = "2019-12-30";
  const params = {
    ImageURLA: imageUrl1,
    ImageURLB: imageUrl2
  };

  callApi(endpoint, action, version, params, callback);
}

/**
 * 处理Base64图片数据
 * @param {string} base64Data Base64图片数据
 * @returns {string} 处理后的Base64字符串
 */
function processBase64Image(base64Data) {
  // 如果包含前缀，去除前缀
  if (base64Data.includes('base64,')) {
    return base64Data.split('base64,')[1];
  }
  return base64Data;
}

/**
 * 活体检测功能
 * @param {string} imageBase64 Base64格式的图片数据
 * @param {Function} callback 结果回调函数
 */
function detectLivingFace(imageBase64, callback) {
  const endpoint = "facebody.cn-shanghai.aliyuncs.com";
  const action = "DetectLivingFace";
  const version = "2019-12-30";
  const params = {
    'Tasks.1.ImageData': processBase64Image(imageBase64)
  };

  callApi(endpoint, action, version, params, callback);
}

/**
 * 生成ISO格式时间戳
 */
function getISOTime() {
  const date = new Date();
  const pad = num => num < 10 ? '0' + num : num;
  return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}T${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}Z`;
}

// uni-app环境下的导出方式
export default {
  callRecognizeFace,
  compareFace,
  detectLivingFace,
  callApi
};
